package il.ac.braude.sona.ui.forms;


import il.ac.braude.ui.forms.questions.FormQuestion;

import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.util.ArrayList;

import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JTextField;



public class FormPanel extends ImagePanel {

	private ArrayList<FormQuestion> mQuestions = new ArrayList<FormQuestion> ();
	private GridBagConstraints mConstraints;
	private class DefaultQuestion extends FormQuestion{
		JTextField tf = new JTextField(20);
		DefaultQuestion(String question) {
			setOpaque(false);
			setLayout(new BoxLayout(this,BoxLayout.X_AXIS));
			JLabel q = new JLabel(question);
			q.setOpaque(false);
			q.setLabelFor(tf);
			add(q);
			add(tf);
			
		}
		void setEditable(boolean isEditable) {
			tf.setEditable(isEditable);
		}
		public void setDefaultAnswer(String defaultAnswer) {
			tf.setText(defaultAnswer);
		}
		public String getAnswer() {
			return tf.getText();
		}

	}

	public FormPanel(String[] questionKeys, Image bg) {
		super(bg);
		init(questionKeys);
	}

	public FormPanel(String[] questionKeys) {
		setOpaque(false);
		setLayout(new GridBagLayout());
		mConstraints = new GridBagConstraints();
		mConstraints.anchor=GridBagConstraints.CENTER;
		for  (int i = 0 ; i < questionKeys.length ; i++) 
			addQuestion(questionKeys[i]);
		setVisible(true);

		revalidate();
	}

	public FormPanel() {
		setOpaque(false);
		setLayout(new GridBagLayout());
		mConstraints = new GridBagConstraints();
	}

	private void init(String[] questionKeys) {
		setOpaque(false);
		setLayout(new GridBagLayout());
		mConstraints = new GridBagConstraints();
		for  (int i = 0 ; i < questionKeys.length ; i++) 
			addQuestion(questionKeys[i]);
	}
	protected ArrayList<String> getResult() {
		ArrayList<String> results = new ArrayList<String>();
		for (FormQuestion q : mQuestions) results.add(q.getAnswer());
		return  results;
	}
	@Override
	public Component add(Component comp) {
		mConstraints.gridy++;
		super.add(comp,mConstraints);
		return this;
		
	}
	public void addQuestion(String question) {
		FormQuestion q = new DefaultQuestion(question);
		mQuestions.add(q);
		add(q);
	}
	public void addQuestions(String[] questionKeys) {
		for  (int i = 0 ; i < questionKeys.length ; i++) 
			addQuestion(questionKeys[i]);
	}
	public void addQuestion(FormQuestion question) {
		mQuestions.add(question);
		add((Component) question);
	}
	public void setDefaultValues(ArrayList<String> values) {
		int size = mQuestions.size();
		for  (int i = 0 ; i < size ; i++) {
			mQuestions.get(i).setDefaultAnswer(values==null || i >= values.size() ? "" : values.get(i));
		}	
	}


}

